var app = getApp();
var ux = require('../../../../lib/ux.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    parma:{},
    validity:0,
    merchant:'',
    msg:'',
    authModle: false,
    phoneModle: false,
    session_key: '',
    banrdId: null,
    click: 'phone',
    openid: '',
    setting: {},
    red: {},
    getSessionKeyUrl: "/api/member/getSessionKey.do",
    getUrl: "/api/balance/getRed.do",
    action: "/api/balance/getRedInfo.do",
    submit: "{{submit}}"
  },
  openAuth: function () {
    this.setData({
      phoneModle: true
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var self = this;
    var memberId = options.memberId;
    var redId = options.redId;
    this.setData({
      merchant: options.merchant,
      memberId: options.memberId,
      redId: options.redId
    })
    wx.setStorageSync("banrdId", options.merchant);
    wx.showLoading({
      title: '加载中.....',
      mask:true
    })
    var parmas = {
      merchant: this.data.merchant,
      memberId: options.memberId,
      redId: options.redId
    }
    ux.redLogin(parmas, function (protocol) {
      if (protocol.data.type == 1) {//已授权
        self.getRedInfos();
      } else if (protocol.data.type == 2) {//未授权
        self.getRedInfos();
        self.setData({
          authModle: true,
        })
      }
    })
  },
  getRedInfos() {
    var self = this;
    var param = {banrnId:this.data.merchant,redId: parseInt(self.data.redId) };
    ux.request(self.data.action, param, function (data) {
      console.log(JSON.stringify(data))
      self.setData({
        parma:data.data.parma,
        validity: data.data.validity,
        setting: data.data.setting,
        red: data.data.red
      })
      if (data.data.red.quantity > 0) {
        self.setData({
          click: "phone"
        })
        self.getSessionKey();
      } else {
        self.setData({
          click: ""
        })
      }
      wx.hideLoading();
    });
  },
  getUserInfoFun: function (e) {
    var self = this;
    var userInfo = e.detail.userInfo
    var params = {};
    params.nickname = userInfo.nickName;
    params.header = userInfo.avatarUrl;
    params.sex = userInfo.gender;
    console.log(JSON.stringify(userInfo));
    wx.showLoading({
      mask: true,
      title: '处理中....',
    })
    wx.login({
      success: function (res) {
        if (res.code) {
          params.jscode = res.code;
          ux.request("/api/member/registerUser.do", params,
            function (protocol) {
              if (protocol.success) {
                wx.setStorageSync("userInfo", protocol.data.userInfo);
                wx.setStorageSync("token", protocol.data.token);
                wx.setStorageSync("setting", protocol.data.setting);
                wx.hideLoading();
                self.setData({
                  authModle: false,
                })
                self.getRedInfos();
              } else {
                wx.hideLoading();
                wx.showToast({
                  title: '系统繁忙!',
                })
              }
            }, true);
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      },
      complete: function (res) {
        console.log(JSON.stringify(res))
      }
    })
  },
  getSessionKey() {
    var self = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          var parmas = { jscode: res.code }
          ux.request(self.data.getSessionKeyUrl, parmas, function (data) {
            self.setData({
              openid: data.data.openid,
              session_key: data.data.session_key
            })
          });
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      },
      complete: function (res) {
        console.log(JSON.stringify(res))
      }
    })
  },
  onForm: function (event) {
    if (this.data.submit) {
      var $this = this;
      var dataset = event.currentTarget.dataset;
      ux.request(this.data.submit, event.detail.value, function (protocol) {
        if (protocol.success) {
          if (dataset.url) {
            wx.redirectTo({ url: dataset.url });
          }
        }
      }, true);
    }
  },

  onTap: function (event) {
    var dataset = event.currentTarget.dataset;
    var data = this.data;
    if (dataset.key && dataset.val) {
      data[dataset.key] = dataset.val;
    }
    this.setData(data);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  preventTouchMoveTy: function () {
    return;
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  getPhoneNumbers: function (e) {
    var self = this;
    var vi = e.detail.iv;
    var encData = e.detail.encryptedData;
    if (!vi) {
      wx.showToast({
        title: '请授权手机号码',
      })
      return false;
    }
    wx.showLoading({
      mask: true,
      title: '处理中....',
    })

    var params = { session_key: self.data.session_key, openid: self.data.openid, redId: self.data.red.id, vi: vi, encData: encData };
    ux.request(self.data.getUrl, params, function (data) {
      wx.hideLoading();
      app.globalData.isShow = true;
      self.toast(data.data.msg);
      self.setData({
        click: 'gotoBanrd',
        phoneModle: false,
        msg: data.data.msg
      })
     
    }, true);
  },
  gotoBanrd: function () {
    wx.reLaunch({
      url: '/pages/member/tab1/sugarSpice?banrdId=' + this.data.merchant +'&userId='+this.data.memberId,
    })
  },
  toast: function (params) {
    if (typeof (params) == "string") {
      params = { content: params };
    }
    this.setData({
      toast: params.content
    });
    var THIS = this;
    setTimeout(function () {
      THIS.setData({
        toast: false
      });
      if (params.complete) {
        params.complete();
      }
    }, params.time || 3000);
  }
})
